import { useNavigate } from 'react-router-dom';
import { LoginIndexWrapper } from './index.styled';
import { Form, Input, Button } from 'antd-mobile';
import { useState } from 'react';
import { EyeInvisibleOutline, EyeOutline, UserOutline, LockOutline } from 'antd-mobile-icons';
import { ILoginForm } from '../../interface/user';
import { userLogin } from '../../store/reducers/user';
import { useAppDispatch } from '../../hooks/redux';

const LoginIndex = () => {
    const navigate = useNavigate();

    // 引入redux相关hook
    // import { useSelector, useDispatch } from 'react-redux';
    // import { RootState } from '../../store';
    // 通过 useSelector 拿到 store 中定义的数据 可以直接使用 redux 暴露的 api 操作，也可以结合 ts 封装 hooks 添加类型后使用
    // const { userInfo } = useSelector((store: RootState) => store.userStore);
    // 通过 dispatch 派发事件
    // const dispatch = useDispatch();

    const dispatch = useAppDispatch();
    // 表单校验规则
    const rules = {
        username: [{ required: true, message: '用户名不能为空' }],
        password: [{ required: true, message: '密码不能为空' }]
    };
    // 密码是否可见
    const [isShowPwd, setIsShowPwd] = useState(false);

    // 提交方法
    const submit = async (val: ILoginForm) => {
        const res = await dispatch(userLogin(val));
        if (res.payload.code) {
            navigate(-1);
        }
    };
    // 提交按钮组件
    const SubmitButton = () => {
        return (
            <Button block type="submit" color="primary" size="large">
                登录
            </Button>
        );
    };
    // 密码是否可见组件
    const ShowPwd = () => {
        return (
            <div>
                {isShowPwd ? (
                    <EyeOutline onClick={() => setIsShowPwd(false)} />
                ) : (
                    <EyeInvisibleOutline onClick={() => setIsShowPwd(true)} />
                )}
            </div>
        );
    };
    return (
        <LoginIndexWrapper>
            <div className="title">登录</div>
            {/* onFinish 表单检验通过后触发的方法 */}
            <Form
                className="form"
                layout="horizontal"
                style={{ '--prefix-width': '20px' }}
                onFinish={submit}
                footer={<SubmitButton />}
            >
                <Form.Item name="username" label={<UserOutline />} rules={rules.username}>
                    <Input clearable placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item name="password" label={<LockOutline />} extra={<ShowPwd />} rules={rules.password}>
                    <Input type={isShowPwd ? 'text' : 'password'} placeholder="请输入密码" />
                </Form.Item>
            </Form>
        </LoginIndexWrapper>
    );
};

export default LoginIndex;
